package com.situ.orderingsystem.servlet;

import com.situ.orderingsystem.global.Global;
import com.situ.orderingsystem.model.User;
import com.situ.orderingsystem.service.LoginService;
import com.situ.orderingsystem.service.impl.LoginServiceImpl;
import com.situ.orderingsystem.utils.BeanFactory;
import com.situ.orderingsystem.utils.Md5Utils;
import com.wf.captcha.base.Captcha;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static java.io.FileDescriptor.out;

@WebServlet("/user/*")
public class LoginServlet extends HttpServlet {
    private final LoginService service = BeanFactory.getBean(LoginServiceImpl.class);
    private HttpServletRequest req;
    private HttpServletResponse resp;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String uri =req.getRequestURI();
            String ctx = req.getContextPath();
            String action = uri.replace(ctx,"");
            if(action.equals("/user/login")){
              //  System.out.println(Md5Utils.encrypt("admin{admin}"));
                String errors = (String) req.getSession().getAttribute("error");
                if(errors != null){
                req.setAttribute("error",errors);
                req.getSession().removeAttribute("error");
                }
                req.getRequestDispatcher("/WEB-INF/login.jsp").forward(req,resp);
            }else if(action.equals("/user/logout")){
                req.getSession().removeAttribute(Global.USER_LOGIN_KEY);
                resp.sendRedirect(req.getContextPath()+"/index");
            } else if (action.equals("/user/edit")) {
                String errors = (String)req.getSession().getAttribute("error");
                if(errors !=null){
                    req.setAttribute("error",errors);
                    req.getSession().removeAttribute("error");
                }
                User user =(User)req.getSession().getAttribute(Global.USER_LOGIN_KEY);
                if(user != null){
                    req.setAttribute("user",user);
                }
                req.getRequestDispatcher("/WEB-INF/user/edit.jsp").forward(req,resp);
            }else  if(action.equals("/user/captcha")){
                CaptchaUtil.out(80,35,4,req,resp);
            }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.req= req;
        this.resp= resp;
        String url = req.getRequestURI();
            String ctx = req.getContextPath();
            String action =url.replace(ctx,"");
            if(action.equals("/user/login")){
                login();
            }else if (action.equals("/user/edit")) {
                edit();
            }

    }
    private void login() throws IOException {

        String userName = req.getParameter("username");
        String passWord = req.getParameter("password");
        String captcha = req.getParameter("captcha");

        boolean c = CaptchaUtil.ver(captcha,req);
        if(!c){
            req.getSession().setAttribute("error","验证码不正确");
            resp.sendRedirect(req.getContextPath()+"/user/login");
            return;
        }
        User user = service.findByUserName(userName);
        if(user == null){
//            System.out.println("用户不存在时");
            req.getSession().setAttribute("error","用户名不存在");
            resp.sendRedirect(req.getContextPath()+"/user/login");
            return;
        }

        Boolean b = service.checkLogin(user,passWord);

        if (b) {
            req.getSession().setAttribute(Global.USER_LOGIN_KEY,user);
            resp.sendRedirect(req.getContextPath()+"/index");
        }else{
            req.getSession().setAttribute("error", "密码不正确");
            resp.sendRedirect(req.getContextPath()+"/user/login");
        }
    }
    private void edit() throws ServletException, IOException {
        User user = (User)req.getSession().getAttribute(Global.USER_LOGIN_KEY);
        if(user == null){
            req.getSession().setAttribute("error","用户不存在，请先登录");
            resp.sendRedirect(req.getContextPath()+"/user/edit");
            return;
        }
        String username = req.getParameter("username");
        if(!StringUtils.hasText(username)){
            req.getSession().setAttribute("error","用户名不能为空");
            resp.sendRedirect(req.getContextPath()+"/user/edit");
            return;
        }
        String password=req.getParameter("password");
        if(!StringUtils.hasText(password)){
            req.getSession().setAttribute("error","旧密码不能为空");
            resp.sendRedirect(req.getContextPath()+"/user/edit");
            return;
        }
        String  newpwd = req.getParameter("newpwd");
        if(!StringUtils.hasText(newpwd)){
            req.getSession().setAttribute("error","新密码不能为空");
            resp.sendRedirect(req.getContextPath()+"/user/edit");
            return;
        }
        String  newpwd2 = req.getParameter("newpwd2");
        if(!StringUtils.hasText(newpwd2)){
            req.getSession().setAttribute("error","确认密码不能为空");
            resp.sendRedirect(req.getContextPath()+"/user/edit");
            return;
        }
        if(!newpwd.equals(newpwd2)){
            req.getSession().setAttribute("error","两次输入密码不一致");
            resp.sendRedirect(req.getContextPath()+"/user/edit");
            return;
        }
        boolean pass = service.checkLogin(user,password);
        if(pass){
           boolean b =service.Update(user,username,newpwd);
           if(b){
               req.getSession().removeAttribute(Global.USER_LOGIN_KEY);
               user.setUserName(username);
               user.setPassWord(newpwd);
               req.getSession().setAttribute(Global.USER_LOGIN_KEY,user);
                req.getRequestDispatcher("/WEB-INF/user/success.jsp").forward(req,resp);
                return;
           }
          else{
               req.getSession().setAttribute("error","保存信息失败请重试");
               resp.sendRedirect(req.getContextPath()+"/user/edit");
               return;
           }
        }
        req.getSession().setAttribute("error","旧密码错误，请重试");
        resp.sendRedirect(req.getContextPath()+"/user/edit");

    }
}
